package org.jeecg.modules.index.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcoding.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DySmsHelper;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.app.userSetting.entity.AppUserSetting;
import org.jeecg.modules.app.userSetting.service.AppUserSettingService;
import org.jeecg.modules.index.service.IndexPageService;
import org.jeecg.modules.message.entity.SysMessage;
import org.jeecg.modules.message.entity.SysMessageTemplate;
import org.jeecg.modules.message.handle.enums.SendMsgStatusEnum;
import org.jeecg.modules.message.service.ISysMessageService;
import org.jeecg.modules.message.service.ISysMessageTemplateService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * @description: APP INDEX SERVICEIMPL
 * @author: zwf
 * @create: 2025-06-12 16:30
 **/
@Slf4j
@Service
public class IndexPageServiceImpl implements IndexPageService {

    @Value("${config.tencent.service-key}")
    private String tencentServiceKey;
    @Value("${config.tencent.reverse-url}")
    private String tencentReverseUrl;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ISysMessageService messageService;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysMessageTemplateService templateService;
    @Resource
    private AppUserSettingService userSettingService;

    /**
     * 地址逆解析（腾讯）
     *
     * @author zwf
     * @date created in 2025/5/10 16:41
     * @param: latLng
     * @return: java.lang.String
     */
    @Override
    public String reverse(JSONObject latLng) {
        if (latLng != null && latLng.containsKey("lat") && latLng.containsKey("lng")) {
            String lat = latLng.getString("lat");
            String lng = latLng.getString("lng");
            // 构建请求 URL
            String requestUrl = tencentReverseUrl + "?location=" + lat + "," + lng + "&key=" + tencentServiceKey;
            // 使用 Hutool 发起 GET 请求
            String response = HttpRequest.get(requestUrl).execute().body();
            // 解析返回的 JSON 数据
            JSONObject jsonResponse = JSON.parseObject(response);
            if (jsonResponse.getInteger("status") == 0) {
                // 返回成功，解析地址信息
                JSONObject result = jsonResponse.getJSONObject("result");
                JSONObject formattedAddress = result.getJSONObject("formatted_addresses");
                String recommend = formattedAddress.getString("recommend");
                return recommend; // 返回格式化地址
            } else {
                // 如果请求失败，返回错误信息
                return "位置信息获取失败";
            }
        }
        return "位置信息获取失败";
    }

    /**
     * 挪车提醒
     *
     * @author zwf
     * @date created in 2025/5/10 17:18
     * @param: params
     * @return: java.lang.String
     */
    @Override
    public Result<String> remind(JSONObject params) {
        Result<String> result = new Result<>();

        if (params != null && params.containsKey("user") && params.containsKey("address")) {
            String userId = params.getString("user");
            String address = params.getString("address");

            SysUser user = userService.getById(userId);
            AppUserSetting userSetting = userSettingService.getByUserId(userId);
            if (userSetting != null) {
                try {
                    if (userSetting.getRemindType() != null && !userSetting.getRemindType().isEmpty() && !"0".equals(userSetting.getRemindType())) {
                        switch (userSetting.getRemindType()) {
                            case "1"://短信
                                result = sendMsg(user, userSetting, address);
                                break;
                            case "2"://邮箱
                                result = sendEmailMsg(user, params);
                                break;
                        }
                    } else {
                        return Result.error("用户已禁用通知");
                    }
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            } else {
                result = Result.error("未获取到用户信息");
            }
            return result;
        } else {
            return Result.error("提醒失败");
        }
    }


    /**
     * 邮箱提醒
     *
     * @author zwf
     * @date created in 2025/5/16 11:50
     * @param: user
     * @param: address
     */
    private Result<String> sendEmailMsg(SysUser user, JSONObject params) {
        try {

            String redisKey = CommonConstant.EMAIL_REMIND_KEY_PRE + user.getId();

            Object object = redisUtil.get(redisKey);

            if (object != null) {
                return Result.ok("已通知，请稍候");
            }

            boolean flag = templateService.sendEmailSms(user.getEmail(), params, "email-remind");

            if (flag) {
                redisUtil.set(redisKey, "ok", 600);
                return Result.ok("提醒成功");
            }
        } catch (Exception e) {
            return Result.error("提醒失败");
        }
        return Result.error("提醒失败");
    }

    /**
     * 短信提醒
     *
     * @author zwf
     * @date created in 2025/5/16 11:50
     * @param: user
     * @param: address
     * @return: org.jeecg.common.api.vo.Result<java.lang.String>
     */
    private Result<String> sendMsg(SysUser user, AppUserSetting userSetting, String address) throws ClientException {

        List<SysMessageTemplate> templates = templateService.selectByCode("sms-remind");

        SysMessageTemplate template = new SysMessageTemplate();

        if (templates != null && templates.size() > 0) {
            template = templates.get(0);
        }

        if (template != null && template.getTemplateContent() != null) {

            String redisKey = CommonConstant.PHONE_REMIND_KEY_PRE + user.getPhone();

            Object object = redisUtil.get(redisKey);

            if (object != null) {
                return Result.ok("已通知，请稍候");
            }

            JSONObject msg = new JSONObject();

            msg.put("hphm", userSetting.getPlateNumber());
            msg.put("address", address);

            Result<String> flag = DySmsHelper.sendMessage(user.getPhone(), msg, JSONObject.parseObject(template.getTemplateContent()));

            SysMessage message = new SysMessage();

            message.setEsTitle("挪车提醒");
            message.setEsType("2");
            message.setEsReceiver(user.getPhone());
            message.setEsParam(JSONObject.toJSONString(msg));
            message.setEsContent("温馨提醒：您的" + userSetting.getPlateNumber() + "在" + address + "，触发挪车提醒，请您及时查看。");
            message.setEsSendTime(new Date());
            message.setEsSendStatus(flag.isSuccess() ? SendMsgStatusEnum.SUCCESS.getCode() : SendMsgStatusEnum.FAIL.getCode());
            message.setEsSendNum(1);
            message.setEsResult(flag.isSuccess() ? flag.getResult() : flag.getMessage());
            message.setCreateBy("admin");
            message.setCreateTime(new Date());
            message.setUpdateBy("admin");
            message.setUpdateTime(new Date());

            messageService.save(message);
            if (flag.isSuccess()) {
                //验证码10分钟内有效
                redisUtil.set(redisKey, "ok", 600);
                return Result.ok("提醒成功");
            } else {
                return Result.error("提醒失败");
            }
        } else {
            return Result.error("提醒失败");
        }
    }

    /**
     * 获取车牌号
     *
     * @author zwf
     * @date created in 2025/5/12 14:22
     * @param: params
     * @return: org.jeecg.common.api.vo.Result<java.lang.String>
     */
    @Override
    public Result<String> getPlateNumber(JSONObject params) {
        AppUserSetting user = userSettingService.getByUserId(params.getString("scene"));

        if (user != null) {
            return Result.ok(user.getPlateNumber());
        } else {
            return Result.error("获取车牌号失败");
        }
    }
}
